package org.example.springchatroom.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.springchatroom.constants.Constants;
import org.example.springchatroom.mapper.UserMapper;
import org.example.springchatroom.model.Result;
import org.example.springchatroom.model.User;
import org.example.springchatroom.utils.JwtUtils;
import org.example.springchatroom.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/9/3
 * Time: 15:17
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result<String> login(String userName, String password,HttpServletRequest request) {
        log.info("login接收到参数,userName:{},password:{}", userName, password);
        //1.参数校验合法性
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空");
        }
        //2.查找用户
        User user = userMapper.login(userName);
        if (user == null) {
            return Result.fail("该用户不存在");
        }
        //3.校验密码
        if (!SecurityUtils.verify(password, user.getPassword())){
            return Result.fail("密码错误");
        }
        //4.生成token
        Map<String,Object> map = new HashMap<>();
        map.put(Constants.TOKEN_ID,user.getUserId());
        map.put(Constants.TOKEN_USERNAME,user.getUserName());
        String token = JwtUtils.generateToken(map);
        log.info("登录完成,生成token:{}",token);
        HttpSession session = request.getSession(true);
        session.setAttribute(Constants.REQUEST_HEADER_TOKEN, token);
        return Result.success(token);
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Result<String> register(String userName,String password){
        log.info("register接收到参数,userName:{},password:{}", userName, password);
        //1.参数校验合法性
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            log.error("用户名或密码为空");
            return Result.fail("用户名或密码为空");
        }
        //2.注册
        User user = new User();
        user.setUserName(userName);
        user.setPassword(SecurityUtils.encrypt(password));
        try {
            Integer ret = userMapper.register(user);
            if (ret == 1) {
                return Result.success("注册成功");
            }
        }catch (Exception e){
            log.error("该用户名已存在");
        }
        return Result.fail("该用户名已存在");
    }

    @RequestMapping(value = "/getLoginUser",method = RequestMethod.GET)
    public Result<User> getLoginUser(HttpServletRequest request) {
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        log.info("getLoginUser接收到参数,token:{}", token);
        Integer userId = JwtUtils.getIdByToken(token);
        if (userId == null) {
            return Result.fail("请先登录");
        }
        User user = userMapper.getUserById(userId);
        log.info("当前登录用户,user:{}", user);
        return Result.success(user);
    }
}
